package com.alm.token.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.ActivityDetailData;
import com.alm.token.ui.data.bean.ActivityIndexData;
import com.alm.token.ui.data.bean.ActivityJoinListData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.ActivityView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LogUtil;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import org.greenrobot.eventbus.EventBus;

import baibeiwallet.activity.TransferActivity1;
import baibeiwallet.event.RefreshActivityEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;

import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_CODE_VAULE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_INTO_CODE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_NAME_VAULE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_SUCC_CODE;
import static com.alm.token.ui.persenter.MyPreenter.draw;
import static com.alm.token.ui.persenter.MyPreenter.pay;

public class ActivityConfirmationActivity extends BaseActivity implements ActivityView<Object> {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;

    @BindView(R.id.tv_buycommit)
    TextView tvBuycommit;
    @BindView(R.id.img_activity_detail_topimg)
    ImageView imgActivityDetailTopimg;
    @BindView(R.id.tv_activity_detail_title)
    TextView tvActivityDetailTitle;
    @BindView(R.id.tv_activity_detail_scannumber)
    TextView tvActivityDetailScannumber;
    @BindView(R.id.img_activity_list_expend)
    ImageView imgActivityListExpend;
    @BindView(R.id.tv_activity_detail_expend)
    TextView tvActivityDetailExpend;
    @BindView(R.id.tv_activity_detail_time)
    TextView tvActivityDetailTime;
    @BindView(R.id.tv_activity_detail_locial)
    TextView tvActivityDetailLocial;
    @BindView(R.id.tv_activity_detail_introducecontent)
    TextView tvActivityDetailIntroducecontent;
    @BindView(R.id.rly_activity_detail)
    RelativeLayout rlyActivityDetail;
    @BindView(R.id.rly_activity_order)
    RelativeLayout rlyActivityOrder;
    @BindView(R.id.img_activity_detail_ordertopimg)
    ImageView imgActivityDetailOrdertopimg;
    @BindView(R.id.tv_activity_detail_ordert_title)
    TextView tvActivityDetailOrdertTitle;
    @BindView(R.id.tv_activity_detail_ordert_locial)
    TextView tvActivityDetailOrdertLocial;
    @BindView(R.id.tv_activity_detail_ordert_time)
    TextView tvActivityDetailOrdertTime;
    @BindView(R.id.tv_activity_detail_order_expend)
    TextView tvActivityDetailOrderExpend;
    @BindView(R.id.tv_buyordercommit)
    TextView tvBuyordercommit;
    @BindView(R.id.ly_top)
    LinearLayout lyTop;

    @BindView(R.id.tv_activity_detail_order_name1)
    TextView tv_activity_detail_order_name1;
    @BindView(R.id.tv_activity_detail_order_name2)
    TextView tv_activity_detail_order_name2;

    @BindView(R.id.tv_activity_detail_order_name)
    TextView tvActivityDetailOrderName;
    @BindView(R.id.tv_activity_detail_order_nameen)
    TextView tvActivityDetailOrderNameen;
    @BindView(R.id.tv_activity_detail_order_country)
    TextView tvActivityDetailOrderCountry;
    @BindView(R.id.tv_activity_detail_order_sex)
    TextView tvActivityDetailOrderSex;
    @BindView(R.id.tv_activity_detail_order_phone)
    TextView tvActivityDetailOrderPhone;
    @BindView(R.id.tv_activity_detail_order_city)
    TextView tvActivityDetailOrderCity;
    @BindView(R.id.tv_activity_detail_order_product)
    TextView tv_activity_detail_order_product;

    @BindView(R.id.tv_activity_detail_order_birthday)
    TextView tvActivityDetailOrderBirthday;
    @BindView(R.id.tv_activity_detail_order_birthplace)
    TextView tvActivityDetailOrderBirthplace;
    @BindView(R.id.tv_activity_detail_order_passportno)
    TextView tvActivityDetailOrderPassportno;
    @BindView(R.id.tv_activity_detail_order_passportissueday)
    TextView tvActivityDetailOrderPassportissueday;
    @BindView(R.id.tv_activity_detail_order_passportexpirydate)
    TextView tvActivityDetailOrderPassportexpirydate;
    @BindView(R.id.tv_activity_detail_order_passportissuplace)
    TextView tvActivityDetailOrderPassportissuplace;
    @BindView(R.id.tv_activity_detail_order_remark)
    TextView tvActivityDetailOrderRemark;

    private ActivityIndexData.DataBean dataBean;
    private ActivityDetailData.DataBean.UserOrderBean userOrderBean;
    private ActivityJoinListData.DataBeanX.DataBean joinDataBean = new ActivityJoinListData.DataBeanX.DataBean();
    private ActivityDetailData.DataBean.ActivityDetailBean activityDetail;
    private ActivityDetailData.DataBean.UserOrderBean userOrder;
    private int staue = -1;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_confirmation;
    }

    @Override
    protected void initVariables() {
        if (getIntent().getSerializableExtra("databean") instanceof ActivityDetailData.DataBean.UserOrderBean) {
            userOrderBean = (ActivityDetailData.DataBean.UserOrderBean) getIntent().getSerializableExtra("databean");
        } else if (getIntent().getSerializableExtra("databean") instanceof ActivityIndexData.DataBean) {
            dataBean = (ActivityIndexData.DataBean) getIntent().getSerializableExtra("databean");
        } else {
            joinDataBean = (ActivityJoinListData.DataBeanX.DataBean) getIntent().getSerializableExtra("databean");
        }
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_orderdetail));
    }

    @Override
    protected void loadData() {
        if (EmptyUtils.isNotEmpty(dataBean)) {
            preenter.getActivityDetailData(EmptyUtils.isNotEmpty(dataBean) ? dataBean.getId() + "" : joinDataBean.getId() + "");
        } else {
            preenter.getActivityUserOrderDetailData(EmptyUtils.isNotEmpty(userOrderBean) ? userOrderBean.getId() + "" : joinDataBean.getId() + "");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_buycommit:

                if (EmptyUtils.isNotEmpty(userOrder)) {
                    new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_orderdetail));
                    rlyActivityDetail.setVisibility(View.GONE);
                    rlyActivityOrder.setVisibility(View.VISIBLE);
                } else {
                    startActivity(ActivityUserInforActivity.class);
                }

                break;
            case R.id.tv_buyordercommit:

                if (EmptyUtils.isNotEmpty(MyApp.getUserData()) && EmptyUtils.isNotEmpty(MyApp.getUserData().getData())) {
                    boolean bindMnemonic = MyApp.getUserData().getData().isBindMnemonic();
                    boolean bindGoogleCode = MyApp.getUserData().getData().isBindGoogleCode();
                    boolean payPwd = MyApp.getUserData().getData().isPayPwd();
                    boolean bindEmail = MyApp.getUserData().getData().isBindEmail();
                    if (!payPwd || !bindEmail) {
                        DialogUtils.toBind(this, getSupportFragmentManager(), payPwd, bindEmail, true, true);
                        break;
                    }
                }

                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.common_warmprompt));
                sysMsgBean.setContent(getString(R.string.tv_hint_activity_warm1));
                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {
                    verify();
                });

//                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {
//
//                    DialogUtils.enterPayPsw(this, (pwd1) -> {
//                        preenter.getActivityPayOrderData(String.valueOf(userOrder.getId()), pwd1);
//                    });
//
////                    verify();
//                });

                break;

            case R.id.ly_top:
//                new ActionBarHelper(this).setTitle("订单详情");
//                rlyActivityDetail.setVisibility(View.VISIBLE);
//                rlyActivityOrder.setVisibility(View.GONE);
                break;
        }
    }

    AlertDialog alert;

    private void verify() {
        alert = DialogUtils.showVerify(this, (pwd, code, google) -> {
            preenter.getActivityPayOrderData(String.valueOf(userOrder.getId()), pwd, code, google);
        }, code1 -> {
            if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
                String phone = MyApp.getUserData().getData().getUser().getPhone();
//                preenter.getSmsCodeData(phone, MyPreenter.pay, code1);
                preenter.getSmsCodeData(MyApp.getMail(), pay);
            }
        }, flag -> {
            LogUtil.e("-------------to_TurnOutBiTBActivity");
            startActivityForResult(FundArealistActivity.class, INTENT_RESULT_INTO_CODE);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == INTENT_RESULT_INTO_CODE && resultCode == INTENT_RESULT_SUCC_CODE && data != null) {
            String name = data.getStringExtra(INTENT_RESULT_NAME_VAULE);
            String code = data.getStringExtra(INTENT_RESULT_CODE_VAULE);
            LogUtil.e("name=" + name + "  code=" + code);

            if (alert != null && alert.isShowing()) {
                if (DialogUtils.getTvClickphonecountry() != null) {
                    DialogUtils.getTvClickphonecountry().setText(name);
                }
                if (DialogUtils.getTvSetphonecode() != null) {
                    DialogUtils.getTvSetphonecode().setText(code);
                }
            }
        }
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void getActivityIndexData(ActivityIndexData activityIndexData) {

    }

    @Override
    public void getActivityDetailData(ActivityDetailData activityDetailData) {


        if (activityDetailData.getStatus() == 0) {
            if (EmptyUtils.isNotEmpty(activityDetailData.getData())) {
                activityDetail = activityDetailData.getData().getActivityDetail();
                userOrder = activityDetailData.getData().getUserOrder();
                ActivityDetailData.DataBean.ProductBean product = activityDetailData.getData().getProduct();

                if (EmptyUtils.isNotEmpty(product)) {
                    tv_activity_detail_order_product.setText(product.getName());
                }


            }
            /**
             * id : 1
             * title : 特使
             * img : http://file.gufang.co/1e9d038c7e500a8f52bc4928956f521.png
             * detailImg : http://file.gufang.co/3a860ddfd773dffde2556039948f164.png
             * price : 15.0
             * moneyType : 1
             * moneyTypeName : ETH
             * moneyTypeImg : http://file.gufang.co/eth_img.png
             * country : 国家
             * city : 城市
             * address : 测试的地址
             * status : 1
             * startTime : 1560147843000
             * endTime : 1561271050000
             * createTime : 1559802255000
             * updateTime : 1560394565000
             * content : 活动内容
             * contentEn : activity content
             * readNum : 0
             */
            if (EmptyUtils.isNotEmpty(activityDetail)) {
                GlideApp.with(this).load(activityDetail.getDetailImg()).into(imgActivityDetailTopimg);
                tvActivityDetailTitle.setText(activityDetail.getTitle());
                tvActivityDetailScannumber.setText(getString(R.string.tv_hint_activity_sacnno, activityDetail.getReadNum() + ""));
                GlideApp.with(this).load(activityDetail.getMoneyTypeImg())
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                if (EmptyUtils.isNotEmpty(resource)) {
//                                    CommonUtil. changeSVGColor(ActivityConfirmationActivity.this, imgActivityListExpend, resource, R.color.black);
//                                    return true;
//                                }
                                return false;
                            }
                        })
                        .error(R.drawable.icon_arctic).into(imgActivityListExpend);
                tvActivityDetailExpend.setText(activityDetail.getPrice() + activityDetail.getMoneyTypeName());
//                tvActivityDetailExpend.setText(activityDetail.getPrice() + " $");
                tvActivityDetailTime.setText(CommonUtil.getDateTimeFromMillisecond2(activityDetail.getStartTime()) + "~" + CommonUtil.getDateTimeFromMillisecond2(activityDetail.getEndTime()));
                tvActivityDetailLocial.setText(activityDetail.getCountry() + activityDetail.getCity() + activityDetail.getAddress());
                tvActivityDetailIntroducecontent.setText(activityDetail.getContent());
            }
            tvBuycommit.setOnClickListener(this);
//            userOrder=new ActivityDetailData.DataBean.UserOrderBean();
//            userOrder.setId(1);
//            userOrder.setOrderId(223);
//            userOrder.setStatus(2);
//            userOrder.setUserPhone("414454");
//            userOrder.setUserRealName("撒大声地");
//            userOrder.setUserRealNameEn("sdsdsds");
            if (EmptyUtils.isNotEmpty(userOrder)) {
                lyTop.setOnClickListener(this);
                new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_orderdetail));
                rlyActivityDetail.setVisibility(View.GONE);
                rlyActivityOrder.setVisibility(View.VISIBLE);
                /**
                 * id : 1
                 * userId : 1627
                 * userRealNameEn : 用户真实英文姓名
                 * userRealName : 真实姓名
                 * phoneAreaCode : 86
                 * userPhone : 17968455
                 * nationality : 中国
                 * userSex : 男
                 * userBirthPlace : 出生地
                 * userBirthTime : 2019-06-05
                 * passportNo : 护照号
                 * passportCreateTime : 2019-06-05
                 * passportEndTime : 2019-06-05
                 * passportAddress : 护照地址
                 * msg : 备注
                 * orderId : 1
                 * status : 3    // 订单状态 2 待支付 3已报名 4 支付失败 5 退回 6 超时 7 取消
                 * createTime : 1560325284000
                 * payTime : 1560325284000
                 * updateTime : null
                 * lastPayTime : null
                 * orderSn :
                 * "city":"城市" // 城市
                 */
                GlideApp.with(this).load(activityDetail.getDetailImg()).into(imgActivityDetailOrdertopimg);
                tvActivityDetailOrdertTitle.setText(activityDetail.getTitle());
                tvActivityDetailOrderExpend.setText(getString(R.string.tv_hint_activity_order_money, activityDetail.getPrice() + activityDetail.getMoneyTypeName()));
//                tvActivityDetailOrderExpend.setText(getString(R.string.tv_hint_activity_order_money, activityDetail.getPrice() + " $"));
                tvActivityDetailOrdertTime.setText(CommonUtil.getDateTimeFromMillisecond2(activityDetail.getStartTime()));
                tvActivityDetailOrdertLocial.setText(activityDetail.getCountry() + activityDetail.getCity());

                tvActivityDetailOrderName.setText(userOrder.getUserRealName());
                tvActivityDetailOrderPhone.setText("+" + userOrder.getPhoneAreaCode() + " " + userOrder.getUserPhone());
                tvActivityDetailOrderNameen.setText(userOrder.getUserRealNameEn());

                tv_activity_detail_order_name1.setText(userOrder.getUserRealSurname());
                tv_activity_detail_order_name2.setText(userOrder.getUserRealSurnameEn());

                tvActivityDetailOrderCountry.setText(userOrder.getNationality());
                tvActivityDetailOrderSex.setText(userOrder.getUserSex().indexOf("0") != -1 ? getString(R.string.tv_hint_activity_user_man) : getString(R.string.tv_hint_activity_user_woman));
                tvActivityDetailOrderCity.setText(userOrder.getCity());
                tvActivityDetailOrderBirthday.setText(userOrder.getUserBirthTime());
                tvActivityDetailOrderBirthplace.setText(userOrder.getUserBirthPlace());
                tvActivityDetailOrderPassportno.setText(userOrder.getPassportNo());
                tvActivityDetailOrderPassportissueday.setText(userOrder.getPassportCreateTime());
                tvActivityDetailOrderPassportexpirydate.setText(userOrder.getPassportEndTime());
                tvActivityDetailOrderPassportissuplace.setText(userOrder.getPassportAddress());
                tvActivityDetailOrderRemark.setText(userOrder.getMsg());


                tvBuyordercommit.setOnClickListener(this);
                staue = userOrder.getStatus();
                //订单状态 2 待支付 3已报名 4 支付失败 5 退回 6 超时 7 取消
                if (staue == 3) {
//                    tvBuycommit.setText("报名详情");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_staue_paysucc));
                    tvBuyordercommit.setOnClickListener(null);
                } else if (staue == 2) {
//                    tvBuycommit.setText("待支付");
//                    tvBuyordercommit.setText("待支付");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_paysubmit1));
                } else if (staue == 4) {
//                    tvBuycommit.setText("支付失败，重新支付");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_paysubmit1));
                } else if (staue == 5) {
//                    tvBuycommit.setText("已退回，重新支付");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_staue_payout));
                    tvBuyordercommit.setOnClickListener(null);
                } else if (staue == 6) {
//                    tvBuycommit.setText("超时，重新支付");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_staue_payout));
                    tvBuyordercommit.setOnClickListener(null);
                } else if (staue == 7) {
//                    tvBuycommit.setText("已取消，重新支付");
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_staue_payout));
                    tvBuyordercommit.setOnClickListener(null);
                } else {
                    tvBuyordercommit.setText(getString(R.string.tv_hint_activity_order_staue_payout));
                    tvBuyordercommit.setOnClickListener(null);
//                    tvBuycommit.setText("立即报名");
                }
            }
        } else {
            showToast(activityDetailData.getMsg());
        }


//        tvActivityDetailIntroducecontent;

    }

    @Override
    public void getActivityJoinData(RegisterData registerData) {

    }

    @Override
    public void getActivityPayOrderData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            EventBus.getDefault().post(new RefreshActivityEvent(1));
            loadData();
        }
    }

    @Override
    public void getActivityJoinListData(ActivityJoinListData activityJoinListData) {

    }

    @Override
    public void getCode(RegisterData registerData) {
//        if (registerData.getMsg().equalsIgnoreCase(getString(R.string.profile_hint_warn15))) {
//            showToast(getString(R.string.profile_hint_warn14));
//        } else {
//            showToast(registerData.getMsg());
//        }
        showToast(registerData.getMsg());
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

//    @OnClick(R.id.tv_buycommit)
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_buycommit:
//
//                startActivity(ActivityUserInforActivity.class);
//                break;
//        }
//    }
}
